/**
 * 认证相关API
 */
import apiClient from './client';
import Taro from '@tarojs/taro';
import { Response, TokenData } from '../types/response';
import { removeToken, setToken } from '../contexts/store';


/**
 * 页面跳转，兼容不同环境
 */
const redirectTo = (url: string): void => {
  try {
    Taro.redirectTo({ url });
  } catch (error) {
    console.error('页面跳转失败:', error);
  }
};


/**
 * 发送手机验证码
 * @param phone - 目标手机号
 * @returns Promise<boolean>
 */
export const sendPhoneCode = async (phone: string): Promise<boolean> => {
  try {
    const response: Response = await apiClient.post('/api/auth/v1/code', { phone });
    if (response.code === 200) {
      return true;
    }
    return false;
  } catch (error) {
    console.error('发送验证码失败:', error);
    throw error;
  }
};


/**
 * 手机号验证码登录
 * @param phone - 手机号
 * @param code - 验证码
 * @returns Promise<boolean>
 */
export const loginWithPhone = async (phone: string, code: string): Promise<Response> => {
  try {
    const response: Response = await apiClient.post('/api/auth/v1/phone', { phone, code });
    if(response.code === 200) {
      const token: TokenData = response.data;
      if (token.access_token) {
        setToken(token.access_token);
      }
    }
    return response;
  } catch (error) {
    console.error('手机号登录失败:', error);
    throw error;
  }
};


/**
 * 用户名/手机号密码登录
 * @param username - 用户名或手机号
 * @param password - 密码
 * @returns Promise<boolean>
 */
export const loginWithPassword = async (phone: string, password: string): Promise<Response> => {
  try {
    const response: Response = await apiClient.post('/api/auth/v1/password', {
      phone,
      password,
    });
    if(response.code === 200) {
      const token: TokenData = response.data;
      if (token.access_token) {
        setToken(token.access_token);
      }
    }
    return response;
  } catch (error) {
    console.error('密码登录失败:', error);
    throw error;
  }
};


/**
 * 微信一键登录 - 按照微信小程序开发流程实现
 */
export const wechatLogin = async (jscode: string): Promise<Response> => {
  try {
    const response: Response = await apiClient.post('/api/auth/v1/wechat', {
      jscode,
    });
    if (response.code === 200) {
      const token: TokenData = response.data;
      if (token.access_token) {
        setToken(token.access_token);
      }
    }
    return response;
  } catch (error) {
    console.error('微信登录失败:', error);
    throw error;
  }
};


/**
 * 退出登录
 */
export const logout = (setToken): void => {
  removeToken(setToken);
  redirectTo('/pages/login/index');
};


/**
 * 用户注册
 * @param username - 用户名
 * @param password - 密码
 * @param phone - 手机号
 * @param code - 验证码
 * @returns Promise<boolean>
 */
export const registerUser = async ({
  username,
  password,
  phone,
  code
}: {username: string, password: string, phone: string, code: string}): Promise<boolean> => {
  try {
    const response: Response = await apiClient.post('/api/auth/v1/register', {
      username,
      password,
      phone,
      code
    });
    if(response.code === 200) {
      const token: TokenData = response.data;
      if (token.access_token) {
        setToken(token.access_token);
        return true;
      }
    }
    return false;
  } catch (error) {
    console.error('用户注册失败:', error);
    throw error;
  }
};


/**
 * 教练用户注册
 * @param phone - 手机号
 * @param code - 验证码
 * @returns Promise<boolean>
 */
export const coachRegisterApi = async ({
  phone,
  code
}: {phone: string, code: string}): Promise<Response> => {
  try {
    const response: Response = await apiClient.post('/api/auth/v1/coach-register', {
      phone,
      code
    });
    return response;
  } catch (error) {
    console.error('用户注册失败:', error);
    throw error;
  }
};

/**
 * 教练用户注册
 * @param phone - 手机号
 * @param code - 验证码
 * @returns Promise<boolean>
 */
export const registerCoachUserApi = async (data): Promise<Response> => {
  try {
    const response: Response = await apiClient.post('/api/coach/v1/register', {
      ...data
    });
    return response;
  } catch (error) {
    console.error('用户注册失败:', error);
    throw error;
  }
};


/**
 * 获取微信用户信息
 * @returns 用户信息对象
 */
export const getWechatUserInfoApi = async (encryptedData: string, iv: string, sessionKey: string): Promise<Response> => {
  try {
    const response: Response = await apiClient.post('/api/user/v1/wechat-user-info', {
      encryptedData: encryptedData,
      iv: iv,
      sessionKey: sessionKey,
    });
    console.log('获取微信用户信息接口调用成功:', response);
    if (response.code === 200) {
      const token: string = response.data;
      if (token) {
        setToken(token);
      }
    }
    return response;
  } catch (error) {
    console.error('获取用户信息接口调用失败:', error);
    throw error;
  }
};

/**
 * 教练用户注册
 * @param phone - 手机号
 * @param code - 验证码
 * @returns Promise<boolean>
 */
export const getCoachRegisterApi = async ({
  phone,
  session_key
}: {phone: string, session_key: string}): Promise<Response> => {
  try {
    const response: Response = await apiClient.get('/api/coach/v1/register', {
      phone,
      session_key
    });
    if(response.code === 200) {
      const token: TokenData = response.data;
      if (token.access_token) {
        setToken(token.access_token);
      }
    }
    return response;
  } catch (error) {
    console.error('获取教练用户注册状态失败:', error);
    throw error;
  }
};